package com.itcs.app.tran;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.itcs.app.service.TransJournalService;
import com.itcs.app.util.PayStatus;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxData;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.util.BoxResUtils;
import com.itcs.box.util.LogUtils;
import com.itcs.dubbo.service.DubboServiceAdapter;
import com.itcs.redis.queue.RedisQueueTemplate;
import com.itcs.trading.mapper.TerminalInfoMapper;
import com.itcs.trading.mapper.TransJournalMapper;
import com.itcs.trading.model.TerminalInfo;
import com.itcs.trading.model.TransJournal;

/**
 * @ClassName: BoxTran1009
 * @Description: 发送车道交易完成结果
 * @author CHEN-HF
 * @date 2017年12月22日 上午11:39:50
 * 
 */
@Component
public class BoxTran1009 implements DubboServiceAdapter {

	private Log logger = LogFactory.getLog(getClass());

	private ExecutorService executorService = Executors.newFixedThreadPool(10);

	@Autowired
	private RedisQueueTemplate redisQueueTemplate;

	@Autowired
	private TransJournalMapper transJournalMapper;
	@Autowired
	private TransJournalService transJournalService;
	
	@Autowired
	private TerminalInfoMapper terminalInfoMapper;

	@Override
	public String getTrancode() {
		return "box_1009";
	}

	public String getTranDescription() {
		return "发送车道交易完成结果";
	}

	@Override
	public Map<String, Object> exchange(Map<String, Object> reqRecord) {

		logger.info(LogUtils.build(getTrancode(), getTranDescription(), "接收发送车道交易完成结果", JSON.toJSONString(reqRecord)));

		Map<String, Object> res = new HashMap<>();
		BoxResponse boxResponse = new BoxResponse();
		BoxData responseData = new BoxData();
		boxResponse.setData(responseData);
		try {
			BoxRequest boxRequest = (BoxRequest) reqRecord.get(BoxConstants.BOX_REQ_KEY);
			boxResponse = this.handle(boxRequest, boxResponse); // 业务处理
		} catch (Exception e) {
			responseData.setResult("-2"); // 解析失败
			logger.error(LogUtils.build(getTrancode(), getTranDescription(), "处理失败," + e.getMessage()), e);
		}
		res.put(BoxConstants.BOX_RES_KEY, boxResponse);

		return res;
	}

	public BoxResponse handle(BoxRequest boxRequest, BoxResponse boxResponse) {
		BoxData boxRequestData = boxRequest.getData();

		try {

			// 主扫、被扫。收到信息，抬标成功
			// 出口车辆白名单主动下发的应答
			String deviceId = boxRequestData.getDeviceId();
			String transacSeq = boxRequestData.getTransacSeq();

			TransJournal traderecord = transJournalService.selectByTransNo(transacSeq);

			if (traderecord == null) {
				logger.warn(LogUtils.build(getTrancode(), getTranDescription(), "交易码:" + transacSeq + ",订单号为空",
						JSON.toJSONString(boxResponse)));
				return BoxResUtils.build2009(boxRequestData, "9");
			}

			if (PayStatus.车道确认支付完成 == traderecord.getPayState()) {
				logger.info(LogUtils.build(getTrancode(), getTranDescription(), "交易码:" + transacSeq + ",已处理完成不在重复处理。"));
				return BoxResUtils.build2009(boxRequestData, "1");
			}

			// 未支付成功的订单，不修改状态为 交易完成
			if (PayStatus.支付成功 != traderecord.getPayState()) {
				logger.info(LogUtils.build(getTrancode(), getTranDescription(),
						"交易码:" + transacSeq + ",未支付成功。" + traderecord.getPayState()));
				return BoxResUtils.build2009(boxRequestData, "9");
			}

			traderecord.setTerminalNo(Long.parseLong(deviceId));
			traderecord.setCarPlate(boxRequestData.getCarPlate());
			traderecord.setPlateColor(Integer.valueOf(boxRequestData.getPlateColor()));
			traderecord.setCarClass(Integer.valueOf(boxRequestData.getCarClass()));
			// etcsTraderecord.setInvoice(Integer.valueOf(boxd.getInvoice()));
			// etcsTraderecord.setTollstationCode(boxd.getiTollStationCode());
			traderecord.setInvoiceState(Integer.valueOf(boxRequestData.getInvoice()));
			traderecord.setiStationId(boxRequestData.getiTollStationCode());
			traderecord.setTollTime(new Date(Long.valueOf(boxRequestData.getRequestTime())));
			
			// 设置出口信息，从通讯盒表中查询出口信息
			TerminalInfo terminalInfo = terminalInfoMapper.selectByPrimaryKey(Long.parseLong(deviceId));
			traderecord.seteLaneId(terminalInfo.getLaneId());
			traderecord.seteTollPlazaId(terminalInfo.getTollPlazaId());
			traderecord.seteStationId(terminalInfo.getStationId());
			
			traderecord.setPayState(PayStatus.车道确认支付完成);// 流程结束

			transJournalMapper.updateByPrimaryKey(traderecord);

			logger.info(
					LogUtils.build(getTrancode(), getTranDescription(), "交易码:" + transacSeq + ",发送车道交易完成结果应答(2009)"));

			// 将交易发送到清算队列
			Send2ClearThread send2ClearThread = new Send2ClearThread(redisQueueTemplate, traderecord);
			executorService.execute(send2ClearThread);

			return BoxResUtils.build2009(boxRequestData, "1");
		} catch (Exception ex) {
			logger.error(LogUtils.build(getTrancode(), getTranDescription(), "处理失败," + ex.getMessage()), ex);
			return BoxResUtils.build2009(boxRequestData, "9");
		}

	}

}
